#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安全工具模块
"""
import hashlib
import secrets
import string
from .config import config


def hash_password(password: str) -> str:
    """密码哈希"""
    return hashlib.sha256(password.encode()).hexdigest()


def generate_password(length: int = 12, use_numbers: bool = True,
                     use_letters: bool = True, use_symbols: bool = False) -> str:
    """生成随机密码"""
    if length < 6 or length > 32:
        raise ValueError("密码长度必须在6-32之间")
    
    characters = ""
    if use_letters:
        characters += string.ascii_letters
    if use_numbers:
        characters += string.digits
    if use_symbols:
        characters += "!@#$%^&*()_+-=[]{}|;:,.<>?"
    
    if not characters:
        raise ValueError("至少需要选择一种字符类型")
    
    password = ''.join(secrets.choice(characters) for _ in range(length))
    return password


def check_password_strength(password: str) -> dict:
    """评估密码强度"""
    strength = {
        'score': 0,
        'feedback': [],
        'strength_level': 'weak'
    }
    
    # 检查长度
    min_length = int(config.get('DEFAULT', 'min_password_length', fallback=8))
    if len(password) >= min_length:
        strength['score'] += 2
        strength['feedback'].append(f'密码长度符合要求 (≥{min_length})')
    else:
        strength['feedback'].append(f'密码长度不足，建议至少{min_length}个字符')
    
    # 检查复杂度
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_symbol = any(not c.isalnum() for c in password)
    
    require_numbers = config.getboolean('DEFAULT', 'require_numbers', fallback=True)
    require_letters = config.getboolean('DEFAULT', 'require_letters', fallback=True)
    require_symbols = config.getboolean('DEFAULT', 'require_symbols', fallback=False)
    
    # 检查是否包含数字
    if require_numbers:
        if has_digit:
            strength['score'] += 1
            strength['feedback'].append('包含数字')
        else:
            strength['feedback'].append('缺少数字')
    
    # 检查是否包含字母
    if require_letters:
        if has_upper or has_lower:
            strength['score'] += 1
            if has_upper and has_lower:
                strength['feedback'].append('包含大小写字母')
                strength['score'] += 1
            else:
                strength['feedback'].append('包含字母')
        else:
            strength['feedback'].append('缺少字母')
    
    # 检查是否包含特殊符号
    if require_symbols:
        if has_symbol:
            strength['score'] += 1
            strength['feedback'].append('包含特殊符号')
        else:
            strength['feedback'].append('缺少特殊符号')
    
    # 常见密码检查 (简化版)
    common_passwords = {'123456', 'password', 'admin', 'welcome', '123456789', '12345678', '12345'}
    if password.lower() in common_passwords:
        strength['feedback'].append('使用了常见密码，容易被破解')
    else:
        strength['score'] += 1
        strength['feedback'].append('未使用常见密码')
    
    # 确定强度等级
    if strength['score'] >= 6:
        strength['strength_level'] = 'strong'
    elif strength['score'] >= 3:
        strength['strength_level'] = 'medium'
    else:
        strength['strength_level'] = 'weak'
    
    return strength